import axios from 'axios'

import type { AxiosInstance, InternalAxiosRequestConfig, AxiosResponse } from 'axios'

// 创建axios实例
const request: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_API_MOCK_PERFIX,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
  },
})

// 请求拦截器
request.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    config.headers = config.headers || axios.defaults.headers
    // 从localStorage获取token
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  },
)

// 响应拦截器
request.interceptors.response.use(
  (response: AxiosResponse) => {
    const { config, data } = response
    if (config.baseURL === "/mock") {
      return data
    } else {
    // 处理真实API的响应格式：{ code: number, message: string, data: any }
    if (data.code === 200) {
      return data.data
    } else {
      return Promise.reject(new Error(data.message || '请求失败'))
    }
    }
  },
  (error) => {
    return Promise.reject(error)
  },
)

export default request
